import React, { PureComponent } from 'react';
import { Balloon, Icon,Feedback } from '@icedesign/base';
import IceImg from '@icedesign/img';
import Layout from '@icedesign/layout';
import Menu from '@icedesign/menu';
import FoundationSymbol from 'foundation-symbol';
import cx from 'classnames';
import { Link, hashHistory } from 'react-router';
import axios from 'axios';
import { headerNavs } from './../navs';
import Logo from './Logo';
import EditDialog from '../pages/UserInfo/components/EditDialog'
import ConfirmDialog from '../pages/Dialog/components/ConfirmDialog'

export default class Header extends PureComponent {
  static displayName = 'UserInfoTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
     loginName:'',
     userID:'',
     record:'',
    };
    this.handleChildChange=this.handleChildChange.bind(this);//监听子组件变化
  }

  componentDidMount() {
    const loginName = sessionStorage.getItem('loginName');  
    const userID = sessionStorage.getItem('userID');
    const record = JSON.parse(sessionStorage.getItem('record'));
    this.setState({"loginName":loginName,"userID":userID,"record":record})
  }

  onOpen=(record,type)=>{
    //record: 编辑时record为当前行的数据记录，添加时为空
    //type: edit编辑 add 添加
    this.refs.getOpenDialog.onOpen(record,type);
  }
  
  loginOut=()=>{
   this.refs.getConfirmDialog.onOpen();
  }

  handleChildChange(status){ 
    //处理子函数传回来的status,status为true，重新请求用户数据，更新sessionStorage
    //status = loginOut 退出登陆
    if(status=='loginOut'){
      axios.get('/api/logout').then((res)=>{
        let data = res.data;
        if(data.code==200 && data.success){
          Feedback.toast.success('即将跳转到登录页面');
          //sessionStorage.clear();
          setTimeout(()=>{
            hashHistory.push('/login');
          },3000) 
        }else{
          Feedback.toast.error(data.msg)
          return;
        }
      }).catch((error)=>{
        Feedback.toast.error('用户数据更新失败，请稍后再试')
        return;
      })
    }else if(status){
      let id = this.state.userID;
      axios.get('/api/users/'+id).then((res)=>{
        if(res.data.code==200 && res.data.success){
          let data = res.data.data;
          //更新sessionStorage和state
          sessionStorage.setItem('loginName',data.loginName)
           sessionStorage.setItem('userID',data.id)
           sessionStorage.setItem('record',JSON.stringify(data))
           this.setState({"loginName":data.loginName,"userID":data.id,"record":data})

        }else{
          Feedback.toast.error(res.data.msg);
          return;
        }
      }).catch((error)=>{
        Feedback.toast.error('用户数据更新失败，请稍后再试')
        return;
      })
      
    }
  }

  render() {
   
    const { width, theme, isMobile, className, style, ...others } = this.props;

    return (
      <Layout.Header
        {...others}
        theme={theme}
        className={cx('ice-design-layout-header', className)}
        style={{ ...style, width }}
      >
        <Logo />
        <EditDialog ref="getOpenDialog" onSaveChange={this.handleChildChange}/>
        <ConfirmDialog ref="getConfirmDialog" text="确认要退出吗？" onChange={this.handleChildChange} />
        <div
          className="ice-design-layout-header-menu"
          style={{ display: 'flex' }}
        >
          {/* Header 菜单项 begin */}
          {headerNavs && headerNavs.length > 0 ? (
            <Menu mode="horizontal" selectedKeys={[]}>
              {headerNavs.map((nav, idx) => {
                const linkProps = {};
                if (nav.newWindow) {
                  linkProps.href = nav.to;
                  linkProps.target = '_blank';
                } else if (nav.external) {
                  linkProps.href = nav.to;
                } else {
                  linkProps.to = nav.to;
                }
                return (
                  <Menu.Item key={idx}>
                    <Link {...linkProps}>
                      {nav.icon ? (
                        <FoundationSymbol type={nav.icon} size="small" />
                      ) : null}
                      {!isMobile ? nav.text : null}
                    </Link>
                  </Menu.Item>
                );
              })}
            </Menu>
          ) : null}
          {/* Header 菜单项 end */}

          {/* Header 右侧内容块 */}

          <Balloon
            trigger={
              <div
                className="ice-design-header-userpannel"
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  fontSize: 12,
                }}
              >
                <IceImg
                  height={40}
                  width={40}
                  src="https://img.alicdn.com/tfs/TB1L6tBXQyWBuNjy0FpXXassXXa-80-80.png"
                  className="user-avatar"
                />
                <div className="user-profile">
                  <span className="user-name" style={{ fontSize: '13px' }}>
                     {this.state.loginName}
                  </span>
                  <br />
                  <span
                    className="user-department"
                    style={{ fontSize: '12px' }}
                  >
                   
                  </span>
                </div>
                <Icon
                  type="arrow-down-filling"
                  size="xxs"
                  className="icon-down"
                />
              </div>
            }
            closable={false}
            className="user-profile-menu"
          >
            <ul>
              <li className="user-profile-menu-item">
                <Link to="/">
                  <FoundationSymbol type="person" size="small" />我的主页
                </Link>
              </li>
              <li className="user-profile-menu-item">
                <Link to="/"  onClick={this.onOpen.bind(this,this.state.record,'edit')}>
                  <FoundationSymbol type="repair" size="small" />设置
                </Link>
              </li>
              <li className="user-profile-menu-item">
                <Link to="/" onClick={this.loginOut}>
                  <FoundationSymbol type="compass" size="small" />退出
                </Link>
              </li>
            </ul>
          </Balloon>
        </div>
      </Layout.Header>
    );
  }
}
